<template>
  <div class="flex-column">
    <div class="flex justify-between flex-row-reverse">
      <div class="text-right flex flex-wrap  justify-end">
        <el-input
          v-model.trim="queryData.keyword"
          style="width: 300px"
          class="mb-10"
          maxlength="32"
          clearable
          :placeholder="$t('SEGMENT_NAME') + '/' + $t('CABLE_NAME') + '/' + $t('RESOURCECODE')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-select
          v-model="stationType"
          clearable
          style="width: 200px"
          class="ml-10 mb-10"
          :placeholder="$t('SELECT_STATION')"
          @change="selectedIds = []"
        >
          <el-option value="no" :label="$t('NOT_A_Z')" />
          <el-option value="a" :label="$t('TRANS_DIRECT_START')" />
          <el-option value="z" :label="$t('TRANS_DIRECT_END')" />
        </el-select>
        <!-- 区域选择 -->
        <!-- 全部区域 -->
        <region-cascader
          v-show="stationType == 'no' || stationType == ''"
          style="width: 280px"
          class="ml-10 mb-10"
          :multiple="true"
          :selected-ids="selectedIds"
          @change="stationChange"
        />
        <!-- 占位用 -->
        <div v-show="stationType == 'no' || stationType == ''" style="width: 280px;" />
        <!-- A端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          style="width: 280px"
          class="ml-10 mb-10"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'A_END_STATION_NAME' : 'Z_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? aStationChange(val) : zStationChange(val)
            }
          "
        />
        <!-- Z端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          class="ml-10 mb-10"
          style="width: 280px"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'Z_END_STATION_NAME' : 'A_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? zStationChange(val) : aStationChange(val)
            }
          "
        />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
      <div class="flex-auto mb-10">
        <el-button v-if="permission.addBtn" type="primary" icon="el-icon-plus" @click="add">{{
          $t('ADD')
        }}</el-button>
        <!-- <el-button
          type="primary"
          icon="el-icon-download"
          @click="exportClick"
        >{{ $t('EXPORT') }}</el-button> -->
      </div>
    </div>
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="130"
      @operate="operate"
      @pageChange="pageChange"
    />
    <edit
      v-if="editShow"
      ref="editBox"
      :set-edit="setEdit"
      :visible="editShow"
      :type="operateType"
      :row-data="rowData"
      @close="closeEdit"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import routeSegmentApi from '@/api/oen/RouteSegmentApi'
  import networkSegmentApi from '@/api/oen/NetworkSegmentApi'
  import { downloadFile, changeDecimal, getParentsById } from '@/utils/common'
  import RegionCascader from '@/components/RegionCascader'
  import Edit from './Edit'
  import TableView from '@/components/TableView'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    name: 'ConfSegmentPage',
    components: {
      Edit,
      RegionCascader,
      TableView
    },
    data() {
      return {
        setEdit: true,
        portInfoVisible: false,
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        queryData: {
          keyword: '',
          startStationIdList: [],
          endStationIdList: [],
          stationIdList: []
        },
        selectedIds: [],
        stationType: '',
        importVisible: false,
        tableData: [],
        rowData: {},
        operateType: 'add',
        editShow: false,
        tableHeader: [
          {
            label: 'SEGMENT_NAME',
            prop: 'segmentName',
            width: 200,
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'A_END_REGIONAL_STATION_NAME',
            prop: 'startStationName',
            width: 200
          },
          {
            label: 'A_END_ROOM_NAME',
            prop: 'startRoomName',
            width: 200,
            configType: 'extend'
          },
          {
            label: 'ANODE',
            prop: 'startNode.nodeName',
            width: 200
          },
          {
            label: 'Z_END_REGIONAL_STATION_NAME',
            prop: 'endStationName',
            width: 200
          },
          {
            label: 'Z_END_ROOM_NAME',
            prop: 'endRoomName',
            width: 200,
            configType: 'extend'
          },
          {
            label: 'ZNODE',
            prop: 'endNode.nodeName',
            width: 200
          },
          {
            label: 'CABLE_NAME',
            prop: 'cable.cableName',
            width: 140
          },
          {
            label: 'CABLE_LENGTH',
            prop: 'cableLength',
            width: 140
          },
          {
            label: 'RESOURCECODE',
            prop: 'resourceCode',
            width: 140
          }
        ]
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'allNodeTypes', 'baseRegionList', 'stationTree']),
      permission() {
        return this.$store.getters.getAuthData('conf:segment')
      }
    },
    watch: {
      editShow(newVal) {
        if (!newVal) return
        this.$nextTick(() => {
          this.$refs.editBox && this.$refs.editBox.open()
        })
      }
    },
    activated() {
      this.loadData()
    },
    methods: {
      loadData() {
        const queryData = {
          ...searchData,
          ...{ page: this.pageData }
        }
        // console.log('queryData', queryData)
        routeSegmentApi.queryPage(queryData).then(res => {
          const list = res.list || []
          list.forEach(i => {
            i.startStationName = this.getRegionName(i.startStationId)
            i.endStationName = this.getRegionName(i.endStationId)
            i.startRoomName = this.getRoomName(i.startNode.roomId)
            i.endRoomName = this.getRoomName(i.endNode.roomId)
            i.resourceCode = i.cable ? i.cable.resourceCode : ''
            i.cableLength = changeDecimal(i.cableLength, 3, true)
            i.btns = this.getBtns(i)
          })
          this.tableData = list
          console.log('this.tableData', this.tableData)
          this.pageData.total = res.total
        })
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'mod',
            show: this.permission.mod,
            label: 'MOD'
          },
          {
            key: 'del',
            show: this.permission.del,
            label: 'DEL'
          }
        ]
        return btns.filter(i => i.show)
      },
      operate(data) {
        switch (data.type) {
        case 'view':
          this.operateType = 'view'
          this.rowData = data.data
          this.editShow = true
          break
        case 'editFibre':
          this.rowData = data.data
          this.portInfoVisible = true
          break
        case 'mod':
          this.operateType = 'mod'
          this.rowData = data.data
          this.editShow = true
          break
        case 'del':
          this.del(data.data)
          break
        }
      },
      // 获取区域/站点
      getRegionName(regionId) {
        const parents = getParentsById(this.stationTree, regionId, 'regionId') || []
        return parents
          .reverse()
          .map(i => i.regionName)
          .join('/')
      },
      // 机房
      getRoomName(roomId) {
        if (!roomId) return ''
        const stationData = this.baseRegionList.find(i => i.regionId === roomId)
        return stationData ? stationData.regionName : ''
      },
      // 区域搜索条件改变
      aStationChange(data) {
        this.queryData.startStationIdList = data
      },
      zStationChange(data) {
        this.queryData.endStationIdList = data
      },
      stationChange(data) {
        this.queryData.stationIdList = data
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        this.queryData.keyword = this.queryData.keyword.trim()
        searchData = {
          ...this.queryData
        }
        this.loadData()
      },
      // 查看详情
      view(row) {
        this.rowData = row
        if (!this.rowData.startNode || !this.rowData.endNode) {
          this.$message.error(this.$t('NODE_ERROR'))
          return
        }
        this.operateType = 'view'
        this.editShow = true
      },
      // 顶部添加
      add() {
        this.operateType = 'add'
        this.rowData = {}
        this.editShow = true
      },
      // 修改
      mod(row) {
        this.rowData = row
        if (!this.rowData.startNode || !this.rowData.endNode) {
          this.$message.error(this.$t('NODE_ERROR'))
          return
        }
        this.operateType = 'mod'
        this.editShow = true
      },
      // 删除
      del(row) {
        // 校验网段是否有例测任务和任务状态
        networkSegmentApi.delVerify({ segmentId: row.segmentId }).then(res => {
          let msg = this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('SEGMENT'), value: row.segmentName })
          const option = {
            type: 'warning',
            confirmButtonText: this.$t('YES'),
            cancelButtonText: this.$t('CANCEL'),
            showConfirmButton: false
          }
          // 提示优先级1.PROCESS("进行中")；2.READY("准备")；3.PLAN("计划")
          if (res === 'PROCESS') {
            msg = this.$t('PROCESS_CAN_NOT_DELETE', { msg: this.$t('SEGMENT') })
          } else if (res === 'READY') {
            msg = this.$t('READY_CONFIRM_DELETE', { msg: this.$t('SEGMENT') })
          } else if (res === 'PLAN') {
            msg = this.$t('PLAN_CONFIRM_DELETE', { msg: this.$t('SEGMENT') })
          } else {
            option.cancelButtonText = this.$t('CANCEL')
            option.showConfirmButton = true
          }
          this.$confirm(msg, option)
            .then(() => {
              routeSegmentApi
                .delBySegmentId({
                  segmentId: row.segmentId,
                  segmentName: row.segmentName
                })
                .then(res => {
                  if (res) {
                    this.$message.success(this.$t('DELETE_SUCCESS'))
                    this.loadData(true)
                  }
                })
            })
            .catch(() => {})
        })
      },
      // 弹窗关闭
      closeEdit(load) {
        this.setEdit = false
        this.$nextTick(() => {
          this.setEdit = true
        })
        this.editShow = false
        if (load === true) {
          this.loadData()
        }
      },
      // 导出文件
      exportClick() {
        const queryData = {
          ...this.queryData,
          ...{ page: this.pageData }
        }
        routeSegmentApi.expData(queryData).then(res => {
          downloadFile(res, `${this.$t('NODE_EXPORT_DATA')}.xlsx`)
        })
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      }
    }
  }
</script>

<style></style>
